//
//  CZHomeViewController.swift
//  CZVVeiBo
//
//  Created by smile on 2017/7/29.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

class CZHomeViewController: CZBaseViewController {
    
    fileprivate lazy var homeListViewModel: CZHomeListViewModel = CZHomeListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            visitorView?.setupVisitorViewInfo(imgName: nil, title: nil)
            return
        }
        setupUI()
        setupTableViewInfo()
        loadData()
    }
    
    // MARK: - 设置tableView相关信息
    func setupTableViewInfo(){
        // 设置数据源
        tableView.dataSource = self
        // 设置代理
        tableView.delegate = self
        // 注册cell
        tableView.register(CZHomeCell.self, forCellReuseIdentifier: "cell")
        // 行高-> 自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        // 设置预估行高(预估行高越接近真实高度越好)
        tableView.estimatedRowHeight = 200
        // cell样式
        tableView.separatorStyle = .none
        // 设置footerView
        tableView.tableFooterView = footerView
        // 添加控件
        tableView.addSubview(refreshControl)

    }
    
    // MARK: - 懒加载控件
    // 自定义上拉加载更多
    fileprivate lazy var footerView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 背景颜色
        view.color = CZAPPThemeColor
        return view
    }()
    // 下拉刷新控件
    fileprivate lazy var refreshControl: CZRefreshControl = {
        let view = CZRefreshControl()
        view.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
        return view
    }()
    // 提示lable
    fileprivate lazy var pullDownTipLabel: UILabel = {
        let lab = UILabel(textColor: UIColor.white, fontSize: 14)
        lab.isHidden = true
        lab.frame = CGRect(x: 0, y: 64 - 30, width: CZSCREENW, height: 30)
        lab.backgroundColor = CZAPPThemeColor
        lab.textAlignment = .center
        return lab
    }()

}
// MARK: - UITableViewDataSource
extension CZHomeViewController: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeListViewModel.dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CZHomeCell
        // 赋值
        cell.homeViewModel = homeListViewModel.dataList[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 判断如果是最后一个cell 要设置菊花的动画 且没有执行动画
        if indexPath.row == homeListViewModel.dataList.count - 1 && !footerView.isAnimating{
            print(indexPath.row)
            // 开启动画
            footerView.startAnimating()
            // 下载数据
            loadData()
        }
    }
}

// MARK: - 请求首页数据
extension CZHomeViewController{
    fileprivate func loadData(){
        //请求数据
        homeListViewModel.getHomeData(isPullUp: footerView.isAnimating) { (isFinish, count) in
            if !isFinish{
                print("请求失败")
            }else{
                if !self.footerView.isAnimating{
                    self.setupPullDownTipLabelAnim(count: count)
                }
                self.tableView.reloadData()
            }
            self.endRefreshing()
        }
    }
    // 设置提示label的动画(首次和下拉刷新)
    fileprivate func setupPullDownTipLabelAnim(count: Int){
        
        // 判断lable是否动画
        if self.pullDownTipLabel.isHidden == false {
            return
        }
        
        // 显示
        self.pullDownTipLabel.isHidden = false
        // 记录显示的文字
        let text: String
        if count > 0 {
            text = "您更新了\(count)条微博"
        }else{
            text = "您已经是最新的微博了"
        }
        // 设置文字
        pullDownTipLabel.text = text
        // 设置动画
        UIView.animate(withDuration: 1, animations: { 
            self.pullDownTipLabel.transform = CGAffineTransform(translationX: 0, y: 30)
        }) { (_) in
            
            // 延迟动画
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: { 
                self.pullDownTipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                // 隐藏
                self.pullDownTipLabel.isHidden = true
            })
        }
    }
    
    // 结束动画
    fileprivate func endRefreshing(){
        self.refreshControl.endRefreshing()
        // 下拉刷新的动画停止
        self.footerView.stopAnimating()
    }
    
    // 监听下拉刷新完成请求数据
    @objc fileprivate func refreshAction(){
        loadData()
    }
}

extension CZHomeViewController{
    // MARK: - 设置视图
    fileprivate func setupUI(){
        setupNav()
        navigationController?.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
    }
    // MARK: - 设置导航
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: nil, imgName: "navigationbar_pop", target: self, action: #selector(leftClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: nil, imgName: "navigationbar_friendsearch", target: self, action: #selector(rightClick))
    }
    
    @objc private func leftClick(){
        print("左侧按钮点击")
        
        
    }
    
    func rightClick(){
        print("右侧侧按钮点击")
        let tempVc = CZTempViewController()
        // 隐藏tabbar
        tempVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(tempVc, animated: true)
    }
}


